﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebSocket4Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Threading;

namespace common
{
    public class websocketWorker
    {
        private WebSocket websocket;
        private string _command;
        public websocketWorker(string command)
        {
            _command = command;
            websocket = new WebSocket("wss://s1.ripple.com", "", WebSocket4Net.WebSocketVersion.Rfc6455);
            websocket.AutoSendPingInterval = 1000;
            websocket.AllowUnstrustedCertificate = true;
            websocket.Opened += new EventHandler(websocket_Opened);
            websocket.Error += new EventHandler<SuperSocket.ClientEngine.ErrorEventArgs>(websocket_Error);
            //websocket.Closed += new EventHandler(websocket_Closed);
            websocket.MessageReceived += new EventHandler<MessageReceivedEventArgs>(websocket_MessageReceived);
            //websocket.DataReceived += new EventHandler<DataReceivedEventArgs>(websocket_DataReceived);
            websocket.Open();
        }
        //public void Worker()
        //{
            
        //}
        public void send(string command)
        {
            //do
            //{
            //    //if (wsw.state == WebSocket4Net.WebSocketState.Open) {

            //    //Console.WriteLine("发送模块状态为：" + state);
            //    //}
            //} while (state == WebSocket4Net.WebSocketState.Connecting);
            
            websocket.Send(command);
        }
        public void websocket_Opened(object sender, EventArgs e)
        {
            Console.WriteLine("*事件*当前连接状态：" + websocket.State);
            websocket.Send(_command);
        }
        public void websocket_Error(object sender, SuperSocket.ClientEngine.ErrorEventArgs e)
        {
            Console.WriteLine("*事件*错误状态：" + e.Exception);
        }
        
        public void websocket_MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            Console.WriteLine("*事件*接到消息：" + e.Message);
            _response = e.Message;
            websocket.Close();
        }
        private string _response=null;
        public string response{
            get {
                //while (_response != null){ return _response; };
                //do
                //{

                //} while (_response == null);
                while (_response == null)
                {

                    Thread.Sleep(0);

                }
                return _response;
            }
        }
        public WebSocketState state
        {
            get { return websocket.State; }
        }
    }

}
